home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / perl5 / Glib / Object / Subclass.pm
Encoding:
Perl POD Document  |  2008-05-04  |  14.2 KB  |  390 lines

  1. # Copyright (C) 2003-2004 by the gtk2-perl team (see the file AUTHORS for
  2. # the full list)
  3. # This library is free software; you can redistribute it and/or modify it under
  4. # the terms of the GNU Library General Public License as published by the Free
  5. # Software Foundation; either version 2.1 of the License, or (at your option)
  6. # any later version.
  7. # This library is distributed in the hope that it will be useful, but WITHOUT
  8. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. # FOR A PARTICULAR PURPOSE.  See the GNU Library General Public License for
  10. # more details.
  11. # You should have received a copy of the GNU Library General Public License
  12. # along with this library; if not, write to the Free Software Foundation, Inc.,
  13. # 59 Temple Place - Suite 330, Boston, MA  02111-1307  USA.
  14. #
  15. # $Header: /cvsroot/gtk2-perl/gtk2-perl-xs/Glib/Subclass.pm,v 1.14 2008/05/04 12:44:22 kaffeetisch Exp $
  16. #
  17.  
  18. package Glib::Object::Subclass;
  19.  
  20. our $VERSION = '0.03';
  21.  
  22. use Glib;
  23.  
  24. =head1 NAME
  25.  
  26. Glib::Object::Subclass - register a perl class as a GObject class
  27.  
  28. =head1 SYNOPSIS
  29.  
  30.   use Glib::Object::Subclass
  31.      Some::Base::Class::,   # parent class, derived from Glib::Object
  32.      signals => {
  33.             something_changed => {
  34.                class_closure => sub { do_something_fun () },
  35.                flags         => [qw(run-first)],
  36.                return_type   => undef,
  37.                param_types   => [],
  38.             },
  39.             some_existing_signal => \&class_closure_override,
  40.      },
  41.      properties => [
  42.         Glib::ParamSpec->string (
  43.            'some_string',
  44.            'Some String Property',
  45.            'This property is a string that is used as an example',
  46.            'default value',
  47.            [qw/readable writable/]
  48.         ),
  49.      ];
  50.  
  51. =head1 DESCRIPTION
  52.  
  53. This module allows you to create your own GObject classes, which is useful
  54. to e.g. implement your own Gtk2 widgets.
  55.  
  56. It doesn't "export" anything into your namespace, but acts more like
  57. a pragmatic module that modifies your class to make it work as a
  58. GObject class.
  59.  
  60. You may be wondering why you can't just bless a Glib::Object into a
  61. different package and add some subs.  Well, if you aren't interested 
  62. in object parameters, signals, or having your new class interoperate
  63. transparently with other GObject-based modules (e.g., Gtk2 and friends),
  64. then you can just re-bless.
  65.  
  66. However, a GObject's signals, properties, virtual functions, and GInterface
  67. implementations are specific to its GObjectClass.  If you want to create
  68. a new GObject which was a derivative of GtkDrawingArea, but adds a new
  69. signal, you must create a new GObjectClass to which to add the new signal.
  70. If you don't, then I<all> of the GtkDrawingAreas in your application
  71. will get that new signal!
  72.  
  73. Thus, the only way to create a new signal or object property in the
  74. Perl bindings for Glib is to register a new subclass with the GLib type
  75. system via Glib::Type::register_object().
  76. The Glib::Object::Subclass module is a Perl-developer-friendly interface
  77. to this bit of paradigm mismatch.
  78.  
  79. =head2 USAGE
  80.  
  81. This module works similar to the C<use base> pragma in that it registers
  82. the current package as a subclass of some other class (which must be a
  83. GObjectClass implemented either in C or some other language).
  84.  
  85. The pragma requires at least one argument, the parent class name.  The
  86. remaining arguments are key/value pairs, in any order, all optional:
  87.  
  88. =over
  89.  
  90. =item - properties => []
  91.  
  92. Add object properties; see L</PROPERTIES>.
  93.  
  94. =item - signals => {}
  95.  
  96. Add or override signals; see L</SIGNALS> and L</OVERRIDING BASE METHODS>.
  97.  
  98. =item - interfaces => []
  99.  
  100. Add GInterfaces to your class; see L</INTERFACES>.
  101.  
  102. =back
  103.  
  104. (Actually, these parameters are all passed straight through to
  105. Glib::Type::register_object(), adding __PACKAGE__ (the current package name)
  106. as the name of the new child class.)
  107.  
  108. =head2 OBJECT METHODS AND FUNCTIONS
  109.  
  110. The following methods are either added to your class on request (not
  111. yet implemented), or by default unless your own class implements them
  112. itself. This means that all these methods and functions will get sensible
  113. default implementations unless explicitly overwritten by you (by defining
  114. your own version).
  115.  
  116. Except for C<new>, all of the following are I<functions> and no
  117. I<methods>. That means that you should I<not> call the superclass
  118. method. Instead, the GObject system will call these functions per class as
  119. required, emulating normal inheritance.
  120.  
  121. =over 4
  122.  
  123. =item $class->new (attr => value, ...)
  124.  
  125. The default constructor just calls C<Glib::Object::new>, which allows you
  126. to set properties on the newly created object. This is done because many
  127. C<new> methods inherited by Gtk2 or other libraries don't have C<new>
  128. methods suitable for subclassing.
  129.  
  130. =item INIT_INSTANCE $self                                 [not a method]
  131.  
  132. C<INIT_INSTANCE> is called on each class in the hierarchy as the object is
  133. being created (i.e., from C<Glib::Object::new> or our default C<new>). Use
  134. this function to initialize any member data. The default implementation
  135. will leave the object untouched.
  136.  
  137. =cut
  138.  
  139. =item GET_PROPERTY $self, $pspec                          [not a method]
  140.  
  141. =item SET_PROPERTY $self, $pspec, $newval                 [not a method]
  142.  
  143. C<GET_PROPERTY> and C<SET_PROPERTY> are called whenever somebody does
  144. C<< $object->get ($propname) >> or C<< $object->set ($propname => $newval) >>
  145. (from other languages, too).  The default implementations hold property
  146. values in the object hash, equivalent to
  147.  
  148.    sub GET_PROPERTY {
  149.      my ($self, $pspec) = @_;
  150.      my $pname = $pspec->get_name;
  151.      return (exists $self->{$pname} ? $self->{$pname}
  152.              : $pspec->get_default_value);  # until set
  153.    }
  154.    sub SET_PROPERTY {
  155.      my ($self, $pspec, $newval) = @_;
  156.      $self->{$pspec->get_name} = $newval;
  157.    }
  158.  
  159. Because C<< $pspec->get_name >> converts hyphens to underscores, a property
  160. C<"line-style"> is in the hash as C<line_style>.
  161.  
  162. These methods let you store/fetch properties in any way you need to.  They
  163. don't have to be in the hash, you can calculate something, read a file,
  164. whatever.
  165.  
  166. Most often you'll write your own C<SET_PROPERTY> so you can take action when
  167. a property changes, like redraw or resize a widget.  Eg.
  168.  
  169.    sub SET_PROPERTY {
  170.      my ($self, $pspec, $newval) = @_;
  171.      my $pname = $pspec->get_name
  172.      $self->{$pname} = $newval; # ready for default GET_PROPERTY
  173.  
  174.      if ($pname eq 'line_style') {
  175.        $self->queue_draw;  # redraw with new lines
  176.      }
  177.    }
  178.  
  179. C<GET_PROPERTY> is different from a C get_property method in that the
  180. perl method returns the retrieved value. For symmetry, the C<$newval>
  181. and C<$pspec> args on C<SET_PROPERTY> are swapped from the C usage.
  182.  
  183. =item FINALIZE_INSTANCE $self                             [not a method]
  184.  
  185. C<FINALIZE_INSTANCE> is called as the GObject is being finalized, that is,
  186. as it is being really destroyed.  This is independent of the more common
  187. DESTROY on the perl object; in fact, you must I<NOT> override C<DESTROY>
  188. (it's not useful to you, in any case, as it is being called multiple
  189. times!).
  190.  
  191. Use this hook to release anything you have to clean up manually.
  192. FINALIZE_INSTANCE will be called for each perl instance, in reverse order
  193. of construction.
  194.  
  195. The default finalizer does nothing.
  196.  
  197. =item $object->DESTROY           [DO NOT OVERWRITE]
  198.  
  199. Don't I<ever> overwrite C<DESTROY>, use C<FINALIZE_INSTANCE> instead.
  200.  
  201. The DESTROY method of all perl classes derived from GTypes is
  202. implemented in the Glib module and (ab-)used for its own internal
  203. purposes. Overwriting it is not useful as it will be called
  204. I<multiple> times, and often long before the object actually gets
  205. destroyed.  Overwriting might be very harmful to your program, so I<never>
  206. do that.  Especially watch out for other classes in your ISA tree.
  207.  
  208. =back
  209.  
  210. =cut
  211.  
  212. *new = \&Glib::Object::new;
  213.  
  214. sub import {
  215.    # we seem to be imported by classes using classes which use us.
  216.    # ignore anything that doesn't look like a registration attempt.
  217.    return unless @_ > 1;
  218.  
  219.    my ($self, $superclass, %arg) = @_;
  220.    my $class = caller;
  221.  
  222.    Glib::Type->register_object(
  223.       $superclass, $class,
  224.       %arg,
  225.    );
  226.  
  227.    # ensure that we have a perlish new().  the old version of this
  228.    # code used a CHECK block to put a new() in if we didn't already
  229.    # have one in the package, but it may be too late to run a CHECK
  230.    # block when we get here.  so, we use the old-fashioned way...
  231.    unshift @{ $class."::ISA" }, __PACKAGE__;
  232. }
  233.  
  234. 1;
  235.  
  236. =head1 PROPERTIES
  237.  
  238. To create gobject properties, supply a list of Glib::ParamSpec objects as the
  239. value for the key 'properties'.  There are lots of different paramspec
  240. constructors, documented in the C API reference's Parameters and Values page,
  241. as well as L<Glib::ParamSpec>.
  242.  
  243. As of Glib 1.060, you can also specify explicit getters and setters for your
  244. properties at creation time.  The default values in your properties are also
  245. honored if you don't set anything else.  See Glib::Type::register_object in
  246. L<Glib::Type> for an example.
  247.  
  248. =head1 SIGNALS
  249.  
  250. Creating new signals for your new object is easy.  Just provide a hash
  251. of signal names and signal descriptions under the key 'signals'.  Each
  252. signal description is also a hash, with a few expected keys.  All the 
  253. keys are allowed to default.
  254.  
  255. =over
  256.  
  257. =item flags => GSignalFlags
  258.  
  259. If not present, assumed to be 'run-first'.
  260.  
  261. =item param_types => reference to a list of package names
  262.  
  263. If not present, assumed to be empty (no parameters).
  264.  
  265. =item class_closure => reference to a subroutine to call as the class closure.
  266.  
  267. may also be a string interpreted as the name of a subroutine to call, but you
  268. should be very very very careful about that.
  269.  
  270. If not present, the library will attempt to call the method named
  271. "do_signal_name" for the signal "signal_name" (uses underscores).
  272.  
  273. You'll want to be careful not to let this handler method be a publically
  274. callable method, or one that has the name name as something that emits the
  275. signal.  Due to the funky ways in which Glib is different from Perl, the
  276. class closures I<should not> inherit through normal perl inheritance.
  277.  
  278. =item return_type => package name for return value.
  279.  
  280. If undefined or not present, the signal expects no return value.  if defined,
  281. the signal is expected to return a value; flags must be set such that the
  282. signal does not run only first (at least use 'run-last').
  283.  
  284. =item accumulator => signal return value accumulator
  285.  
  286. quoting the Glib manual: "The signal accumulator is a special callback function
  287. that can be used to collect return values of the various callbacks that are
  288. called during a signal emission."
  289.  
  290. If not specified, the default accumulator is used, and you just get the 
  291. return value of the last handler to run.
  292.  
  293. Accumulators are not really documented very much in the C reference, and
  294. the perl interface here is slightly different, so here's an inordinate amount
  295. of detail for this arcane feature:
  296.  
  297. The accumulator function is called for every handler.  It is given three
  298. arguments: the signal invocation hint as an anonymous hash (containing the
  299. signal name, notably); the current accumulated return value; and the value
  300. returned by the most recent handler.  The accumulator must return two values:
  301. a boolean value determining whether signal emission should continue (false
  302. stops the emission), and the new value for the accumulated return value.
  303. (This is different from the C version, which writes through the return_accu.)
  304.  
  305. =back
  306.  
  307. =head1 OVERRIDING BASE METHODS
  308.  
  309. GLib pulls some fancy tricks with function pointers to implement methods
  310. in C.  This is not very language-binding-friendly, as you might guess.
  311.  
  312. However, as described above, every signal allows a "class closure"; you
  313. may override thie class closure with your own function, and you can chain
  314. from the overridden method to the original.  This serves to implement
  315. virtual overrides for language bindings.
  316.  
  317. So, to override a method, you supply a subroutine reference instead of a
  318. signal description hash as the value for the name of the existing signal
  319. in the "signals" hash described in L</SIGNALS>.
  320.  
  321.   # override some important widget methods:
  322.   use Glib::Object::Subclass
  323.         Gtk2::Widget::,
  324.     signals => {
  325.         expose_event => \&expose_event,
  326.         configure_event => \&configure_event,
  327.         button_press_event => \&button_press_event,
  328.         button_release_event => \&button_release_event,
  329.         motion_notify_event => \&motion_notify_event,
  330.         # note the choice of names here... see the discussion.
  331.         size_request => \&do_size_request,
  332.     }
  333.  
  334. It's important to note that the handlers you supply for these are
  335. class-specific, and that normal perl method inheritance rules are not
  336. followed to invoke them from within the library.  However, perl code can
  337. still find them!  Therefore it's rather important that you choose your
  338. handlers' names carefully, avoiding any public interfaces that you might
  339. call from perl.  Case in point, since size_request is a widget method, i
  340. chose do_size_request as the override handler.
  341.  
  342. =head1 INTERFACES
  343.  
  344. GObject supports only single inheritance; in place of multiple inheritance,
  345. GObject uses GInterfaces.  In the Perl bindings we have mostly masqueraded
  346. this with multiple inheritance (that is, simply adding the GInterface class
  347. to the @ISA of the implementing class), but in deriving new objects the
  348. facade breaks and the magic leaks out.
  349.  
  350. In order to derive an object that implements a GInterface, you have to tell
  351. the GLib type system you want your class to include a GInterface.  To do
  352. this, simply pass a list of package names through the "interfaces" key;
  353. this will add these packages to your @ISA, and cause perl to invoke methods
  354. that you must provide.
  355.  
  356.   package Mup::MultilineEntry;
  357.   use Glib::Object::Subclass
  358.       'Gtk2::TextView',
  359.       interfaces => [ 'Gtk2::CellEditable' ],
  360.       ;
  361.  
  362.   # perl will now invoke these methods, which are part of the
  363.   # GtkCellEditable GInterface, when somebody invokes the
  364.   # corresponding lower-case methods on your objects.
  365.   sub START_EDITING { warn "start editing\n"; }
  366.   sub EDITING_DONE { warn "editing done\n"; }
  367.   sub REMOVE_WIDGET { warn "remove widget\n"; }
  368.  
  369. =head1 SEE ALSO
  370.  
  371.   GObject - http://developer.gnome.org/doc/API/2.0/gobject/
  372.  
  373. =head1 AUTHORS
  374.  
  375. Marc Lehmann E<lt>schmorp@schmorp.deE<gt>, muppet E<lt>scott at asofyet dot orgE<gt>
  376.  
  377. =head1 COPYRIGHT AND LICENSE
  378.  
  379. Copyright 2003-2004 by muppet and the gtk2-perl team
  380.  
  381. This library is free software; you can redistribute it and/or modify
  382. it under the terms of the Lesser General Public License (LGPL).  For 
  383. more information, see http://www.fsf.org/licenses/lgpl.txt
  384.  
  385. =cut
  386.  
  387.